package com.fly.flowdemo.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Button;

import com.fly.flowdemo.R;

/**
 * Created with Android Studio.
 * Package_Name：com.fly.flowdemo.view
 * Project_Name：FlowDemo
 * User：郭鹏飞
 * Date：2015/12/11
 * Email：love518420@foxmail.com
 * Description：
 */
public abstract class ButtonFlowLayout extends FlowLayout {

    protected int normlaResId = R.drawable.btn_default_normal, selectedResId = R.drawable.btn_default_selected;

    public ButtonFlowLayout(Context context) {
        this(context, null);
    }

    public ButtonFlowLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ButtonFlowLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        TypedArray typedArray = context.obtainStyledAttributes(attrs,
                R.styleable.ButtonFlowLayout, defStyleAttr, 0);
        int count = typedArray.getIndexCount();
        for (int i = 0; i < count; i++) {
            int index = typedArray.getIndex(i);
            if (index == R.styleable.ButtonFlowLayout_itemNormalBackground) {
                normlaResId = typedArray.getResourceId(index, R.drawable.btn_default_normal);
            } else if (index == R.styleable.ButtonFlowLayout_itemSelectedBackground) {
                selectedResId = typedArray.getResourceId(index, R.drawable.btn_default_selected);

            }
        }

        typedArray.recycle();
    }

    /**
     * 清空选中状态
     */
    public void clearChooseStatus() {
        for (int i = 0; i < getChildCount(); i++) {
            View view = getChildAt(i);
            view.setBackgroundResource(normlaResId);
        }
    }

    /**
     * 设置标签
     *
     * @param labels 集合
     */
    public void setLabels(String[] labels) {
        if (labels == null || labels.length == 0) {
            throw new NullPointerException("标签为空");
        }
        for (int i = 0; i < labels.length; i++) {
            Button button = new Button(context);
            button.setText(labels[i]);
            button.setBackgroundResource(normlaResId);
            final int position = i;
            button.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    dealWithClickEvent(view, position);
                }
            });
            addView(button);
        }
    }

    /**
     * 处理点击事件
     *
     * @param view     点击对象
     * @param position 点击对象的位置
     */
    protected abstract void dealWithClickEvent(View view, int position);

}
